package edu.ustb.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    //定义一个常量
    public static final String CONFIG_FILE = "MapConfig.xml";
    //创建会话工厂对象，静态代码块
    static SqlSessionFactory factory;
    static {
        initFactory(CONFIG_FILE);
    }

    private static void initFactory(String configFile) {
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        try{
            InputStream inputStream = Resources.getResourceAsStream(configFile);
            factory = sqlSessionFactoryBuilder.build(inputStream);
        }
        catch (IOException ioException)
        {
            ioException.printStackTrace();
        }
    }

    //本地线程
    static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    //获取SqlSession
    public static SqlSession open()
    {
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession==null)
        {
            sqlSession = factory.openSession(true);
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }
    //释放SqlSession
    public static void close()
    {
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession!=null)
        {
            sqlSession.close();
            threadLocal.set(null);
        }
    }
    //事务对象
    public static void commit()
    {
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession!=null)
        {
            sqlSession.commit();
        }
    }
    //事务回滚
    public static void rollBack()
    {
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession!=null)
        {
            sqlSession.rollback();
        }
    }
    public static <T> T getMapper(Class<T> tClass)
    {
        return open().getMapper(tClass);
    }
}
